<template>
  <div classs="exportDown">
    <!-- 导出下载中心 -->
    <div class="exportBg">
      <div class="box-card">
        <!-- 单选 -->
        <div class="firstLevel">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="路线" name="first">
              <organization-unit v-model="exportForm.deptTreeId" :change-on-select="true" placeholder="选择管养单位"
                                 @change="changeDept"></organization-unit>
            </el-tab-pane>
            <el-tab-pane label="区间" name="second">
              <organization-unit v-model="exportForm.deptTreeId" :change-on-select="true" placeholder="选择管养单位"
                                 @change="changeDept"></organization-unit>
              <div style="margin-top: 20px">
                <el-select v-model="exportForm.roadId" filterable clearable placeholder="选择路线">
                  <el-option v-for="item in deptRoadList" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </div>
            </el-tab-pane>
            <el-tab-pane label="地质灾害档案" name="third">
              <organization-unit v-model="exportForm.deptTreeId" :change-on-select="true" placeholder="选择管养单位"
                                 @change="changeDept"></organization-unit>
              <div style="margin-top: 20px">
                <el-select v-model="exportForm.roadId" filterable clearable placeholder="选择路线">
                  <el-option
                    v-for="item in deptRoadList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </div>
            </el-tab-pane>
            <el-tab-pane label="边坡档案" name="fourth">
              <organization-unit
                v-model="exportForm.deptTreeId"
                :change-on-select="true"
                placeholder="选择管养单位"
                @change="changeDept"></organization-unit>
              <div style="margin-top: 20px">
                <el-select v-model="exportForm.roadId" filterable clearable placeholder="选择路线">
                  <el-option
                    v-for="item in deptRoadList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </div>
            </el-tab-pane>
            <el-tab-pane label="技术状况评定" name="five">
              <organization-unit
                v-model="exportForm.deptTreeId"
                :change-on-select="true"
                placeholder="选择管养单位"
                @change="changeDept"></organization-unit>
              <div style="margin-top: 20px">
                <el-select v-model="exportForm.roadId" filterable clearable placeholder="选择路线">
                  <el-option
                    v-for="item in deptRoadList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
                <el-select style="margin-left: 1vw" v-model="exportForm.type" filterable placeholder="选择年份">
                  <el-option
                    label="首次"
                    value="1">
                  </el-option>
                  <el-option
                    label="所有"
                    value="2">
                  </el-option>
                </el-select>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div class="footLevel">
          <el-button @click="open"> 导出数据</el-button>
        </div>
      </div>
    </div>
    <!-- 下载列表 -->
    <div class="downloadBg">

      <el-divider content-position="left"><span style="font-size: 20px;color: #1990FE">导出记录</span></el-divider>
      <el-button icon="el-icon-refresh-left" style="margin-top: 1vw" @click="getList()">
        刷新
      </el-button>
      <div class="common_btnBox">

        <i class="iconfont iconzongshu icon-size"></i>
        总数：{{form.total}}
      </div>
      <el-table :data="tableData" border>
        <el-table-column prop="fileName" label="文件名" min-width="250"></el-table-column>
        <el-table-column prop="downloadTypeName" label="导出类型">
        </el-table-column>
        <el-table-column prop="count" label="数据数量（条）"></el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
        <el-table-column prop="createTime" label="导出时间">
          <template slot-scope="scope">
            {{ scope.row.createTime | formatTimer() }}
          </template>
        </el-table-column>
        <el-table-column prop="operator" label="操作人"></el-table-column>
        <el-table-column prop="operation" label="操作">
          <template slot-scope="scope">
            <p v-if="scope.row.count==0" style="color: red">没有需要导出的数据</p>
            <p v-else-if="!scope.row.count" style="color: #1990FE;">正在导出中...</p>
            <a v-else style="background: #1990FE; color: white" :href="constUrl + scope.row.url"
               :download="scope.row.fileName + '.zip'">
              <el-button style="background:#1990FE;color: white;" size="mini">
                下载
              </el-button>

            </a>
            <el-popconfirm confirmButtonText='好的'
                           cancelButtonText='不用了' icon="" title="确定删除吗？" @confirm="handleDelete(scope.row.id)">
              <button slot="reference" class="btn_delete" style="margin-left: 1vw">删除</button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="form.page"
        :page-size="form.pageSize"
        :page-sizes="[10, 20, 30, 40,50,60,70,80,90,100]"
        layout="sizes, prev, pager, next"
        :total="form.total">
      </el-pagination>
    </div>
    <x-loading v-show="isLoading"></x-loading>

  </div>

</template>

<script>
  // 引入拼接地址
  import constUrl from "@/services/env";
  import Format from "@/utils/format";
  import {getDownload, deleteDownload} from "@/services/model/download";
  import {getRoadSelectList} from "@/services/model/road-mgmt";
  import OrganizationUnit from "@/components/organization-unit/all";
  import {
    getSlopeFile,
    getInterval,
    getRoute,
    getGroundDisaster, getSlopeTechnique
  } from "@/services/model/export";
  import {Message} from "element-ui";
  import XLoading from '@/components/animation/x-loading.vue'

  export default {
    components: {OrganizationUnit, XLoading},
    data() {
      return {
        isLoading: false,
        uuid: '',
        ws: null,
        // 接入地址
        constUrl,
        // 列表数据
        tableData: [],
        form: {
          page: 1,
          pageSize: 10,
          total: 0,
          downloadType: 3
        },
        downloadTypes: [],
        activeName: "first",
        // 控制默认
        radio1: "路线",
        value: [],
        // 选择路线
        roadId: "",
        // 选择标段
        // 选择边坡
        slopeId: "",
        exportForm: {type: '1'},
        deptRoadList: [],
        remark: ''
      };
    },
    filters: {
      // 时间格式化
      formatTimer(timer) {
        return Format(new Date(timer));
      },
    },
    methods: {
      //删除
      async handleDelete(id) {
        let res = await deleteDownload({id: id})
        if (res.code === 200) {
          this.$notify({
            type: 'success',
            title: '提示',
            message: '删除成功'
          })
        }
        this.getList()
      },
      getUUID() {
        var s = []
        var hexDigits = '0123456789abcdef'
        for (var i = 0; i < 36; i++) {
          s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
        }
        s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = '-'
        var uuid = s.join('')
        return uuid
      },
      //连接socket
      connectSocket() {
        this.uuid = this.getUUID();
        let uuid = this.uuid
        if ('WebSocket' in window) {
          // 打开一个 web socket
          // 8.134.64.118:9093
          this.ws = new WebSocket(`ws://8.134.54.223:9999/webSocket/file/upload/${uuid}`)
          this.ws.onopen = function () {
            console.log('websocket 连接上')
          }
          // 连接
          this.ws.onmessage = (evt) => {
            console.log(evt)
            let mes = JSON.parse(evt.data)
            if (mes.code == 200) {
              this.getList();

            } else {
              this.$notify({
                type: 'error',
                title: '提示',
                message: mes.message
              })

            }
          }

          this.ws.onerror = function (err) {
          }
        } else {
          // 浏览器不支持 WebSocket
          Message({
            type: 'warning',
            message: '您的浏览器不支持 WebSocket!'
          })
        }
      },
      // 弹窗
      open() {
        if (!this.exportForm.deptTreeId) {
          this.$message({
            type: 'warning',
            message: '先选择管养单位！'
          });
          return
        }
        this.$prompt('请输入备注', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          center: true
        }).then(({value}) => {

          this.remark = value
          this.toDownload()

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          });
        });
      },

      // 判断tab选择名
      JudgeActiveName() {
        this.isLoading = true
        if (this.activeName == "first") {
          this.getLuXian();
        } else if (this.activeName == "second") {
          this.getQuJian();
        } else if (this.activeName == "third") {
          this.getDiZai();
        } else if (this.activeName == "fourth") {
          this.getBianPo();
        } else {
          this.getJiShu()
        }

      },
      //获取组织下的路线列表
      async getRoadListByDept(deptId) {
        const {data} = await getRoadSelectList({deptId: deptId});
        return data;
      },
      // 获取路线
      async changeDept() {
        this.deptRoadList = await this.getRoadListByDept(this.exportForm.deptTreeId);
        this.depList();
      },
      depList() {
        this.deptRoadList.map(function (items, index, array) {
          return index;
        });
      },
      // 跳转到下载页面
      toDownload() {
        this.JudgeActiveName();
      },
      handleChange(value) {
      },
      // 导出路线
      async getLuXian() {
        let res = await getRoute({deptTreeId: this.exportForm.deptTreeId, remark: this.remark, uuid: this.uuid});
        this.isLoading = false
        if (res.code === 200) {
          this.getList();
        }
      },
      //技术状况评定导出
      async getJiShu() {
        let res = await getSlopeTechnique({
          deptTreeId: this.exportForm.deptTreeId,
          roadId: this.exportForm.roadId,
          type: this.exportForm.type,
          remark: this.remark,
          uuid: this.uuid,
        });
        this.isLoading = false
        if (res.code === 200) {
          this.getList();
        }
      },
      // 边坡档案导出
      async getBianPo() {
        let res = await getSlopeFile({
          deptTreeId: this.exportForm.deptTreeId,
          roadId: this.exportForm.roadId,
          remark: this.remark,
          uuid: this.uuid
        });
        this.isLoading = false
        if (res.code === 200) {
          this.getList();
        }
      }, //区间导出
      async getQuJian() {
        let res = await getInterval({
          deptTreeId: this.exportForm.deptTreeId,
          roadId: this.exportForm.roadId,
          remark: this.remark,
          uuid: this.uuid
        });
        this.isLoading = false
        if (res.code === 200) {
          this.getList();
        }
      }, //地灾档案导出
      async getDiZai() {
        let res = await getGroundDisaster({
          deptTreeId: this.exportForm.deptTreeId,
          roadId: this.exportForm.roadId,
          remark: this.remark,
          uuid: this.uuid
        });
        this.isLoading = false
        if (res.code === 200) {
          this.getList();
        }
      },
      // tab 切换时候的事件
      handleClick(tab, event) {
        if (tab.label == '边坡档案') {
          this.form.downloadType = 1
        } else if (tab.label == '地质灾害档案') {
          this.form.downloadType = 2
        } else if (tab.label == '路线') {
          this.form.downloadType = 3
        } else if (tab.label == '区间') {
          this.form.downloadType = 4
        } else if (tab.label == '技术状况评定') {
          this.form.downloadType = 5
        }

        console.log(tab.label, this.form.downloadType)
        this.getList()
      },
      // 获取下载数据
      async getList() {
        let res = await getDownload(this.form);
        this.tableData = res.data?.records || [];
        this.form.page = Number(res.data?.current);
        this.form.total = Number(res.data?.total);
      },
      // 分页大小改变
      handleSizeChange(val) {
        this.form.pageSize = val;
        this.getList();
      },
      // 当前页码改变
      handleCurrentChange(val) {
        this.form.page = val;
        this.getList();
      },
      //获取路线列表
    },
    created() {
      this.getList();
    },
    activated() {
      this.getList();
    },
    mounted() {
      this.connectSocket()

      this.getList();
    },

    beforeDestroy() {
      this.ws.onclose = function (e) { // 监听关闭
        // this.ws.close()
        console.log('连接已关闭...')
      }
    }
  };
</script>

<style lang="less" scoped>
  .exportDown {
    width: 100vw;
    height: 100vh;

    overflow: hidden;
  }

  .exportBg {
    width: 80%;
    height: 100%;
    margin: auto;
    margin-top: 10px;
    box-shadow: 0px 0px 8px black;

    .box-card {
      width: 100%;
      height: 270px;
      color: white;
      overflow: hidden;

      .firstLevel {
        margin: auto;
        margin-top: 20px;
        width: 90%;
        height: 160px;

        /deep/ .el-tabs__item {
          color: black;
          width: 50%;
          text-align: center;
          box-sizing: border-box;
          font-size: 16px;
        }

        /deep/ .el-tabs__item.is-active {
          color: white;
          background-color: #1990FE;
          font-size: 140%;
          box-sizing: border-box;
        }


        /deep/ .el-tabs__active-bar {
          background-color: #1990FE !important;
        }
      }

      .footLevel {
        width: 100%;
        height: 50px;
        // background: red;
        position: relative;

        /deep/ .el-button {
          background: #1990FE;
          color: white;
          border: none;
          position: absolute;
          bottom: 0;
          right: 10%;
        }

        // 修改弹窗
      }
    }
  }

  .downloadBg {
    margin: auto;
    margin-top: 20px;
    width: 80%;
    box-sizing: border-box;
    padding: 10px;
    box-shadow: 0px 0px 8px black;

    /deep/ .el-table {
      margin: auto;
      margin-top: 20px !important;
    }

    /deep/ .el-button {
      background: #1990FE;
      color: white;
    }

    .el-pagination {
      margin: auto;
      margin-top: 20px;
      width: 80%;
    }
  }

  // 修改下拉菜单 宽度
  /deep/ .el-cascader {
    margin: auto;
    position: relative;
    width: 100%;

    .el-input {
      margin-right: 20px;
    }
  }

</style>


<style lang="less">

  .el-message-box__header {
    background: #1990FE !important;

    span {
      color: white;
      font-size: 22px;
    }

  }

  .el-message-box {
    // background: yellow !important;
  }

  .el-message-box__headerbtn .el-message-box__close {
    color: white;
  }

  .el-message-box__message {
    margin-top: 20px;
    color: #1990FE;
    font-size: 20px;
  }

  .el-message-box__btns {

  }

  // background: #1990FE;


</style>
